from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.shortcuts import render_to_response
from profile.models import *
from django.core.exceptions import ObjectDoesNotExist
from django.core.urlresolvers import reverse
from django.contrib import auth
from django import forms
from django.template import RequestContext
from django.http import HttpResponseRedirect
from django.http import HttpResponse
from django.utils.safestring import mark_safe
from django.shortcuts import get_object_or_404
import json

def is_friends(user, userid):
    for friend in user.userprofile.friends.all:
        if friend.userid == userid:
            return True
    return False

@login_required
def add(request):
    args = dict(request.GET.items())
    current_user = request.user.get_profile()
    success = False
    try:
        uid = args['uid'] if 'uid' in args else None
        if 'name' in args:
            new_friend = auth.models.User.objects.get(username = args['name']).get_profile()
        else:
            new_friend = auth.models.User.objects.get(pk = uid).get_profile()
        
        current_user.friends.add(new_friend)
        success = True
    except: pass
    return HttpResponse(json.dumps({'success': success}), mimetype = 'application/json')
    
    """
    if request.method == "POST":
        form = AddFriendForm(request.POST)
        form.current_user = request.user
        if form.is_valid():
            friend_username = form.cleaned_data['friend']
            new_friend = auth.models.User.objects.get(username=friend_username).get_profile()

            current_user = request.user.get_profile()
            current_user.friends.add(new_friend)
            current_user.save()
            form = AddFriendForm()
            form.current_user = request.user
            if not request.is_ajax():
                return HttpResponseRedirect(reverse('profile.detail.display'))
    elif user_id is not None:
        new_friend = get_object_or_404(UserProfile,pk=user_id)

        form = AddFriendForm()
        form.current_user = request.user
        form.cleaned_data = {}
        form.cleaned_data['friend'] = new_friend.user.username
        try:
            form.clean()
            current_user = request.user.get_profile()
            current_user.friends.add(new_friend)
            current_user.save()
            form = AddFriendForm()
            form.current_user = request.user
        except:
            pass
        if not request.is_ajax():
            return HttpResponseRedirect(reverse('profile.detail.display'))
        
    else:
        form = AddFriendForm()
        form.current_user = request.user

    return render_to_response( "add_friend.html", {'form':form},
            context_instance=RequestContext(request)
            )
    """

@login_required
def remove(request):
    success = False
    current_user = request.user.get_profile()
    remove_friend = get_object_or_404(UserProfile, pk=request.GET['uid'])
    try:
        current_user.friends.remove(remove_friend)
        success = True
    except: pass
    return HttpResponse(json.dumps({'success': success}), mimetype = 'application/json')

def friends_list(request):
    return render_to_response("friends_list.html",
                              context_instance=RequestContext(request))

